package com.littlebee.storychild.ui;

import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.flyco.tablayout.SlidingTabLayout;
import com.littlebee.storychild.R;
import com.littlebee.storychild.common.BaseApplication;
import com.littlebee.storychild.common.utils.Constant;
import com.littlebee.storychild.common.utils.LogUtil;
import com.littlebee.storychild.common.utils.NetWorkUtils;
import com.littlebee.storychild.common.utils.ToastUtil;
import com.littlebee.storychild.common.utils.Utils;
import com.littlebee.storychild.ui.entry.Cartoons;
import com.littlebee.storychild.ui.entry.User;
import com.tuliu.appupdate.updatelib.UpdateManager;
import com.zss.library.PermissionCallBack;
import com.zss.library.activity.BaseActivity;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;
import com.zss.library.utils.SharedPrefUtils;
import com.zss.library.widget.CommonProgressDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.ContactManager;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.event.ContactNotifyEvent;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;

public class MainActivity extends BaseActivity implements View.OnClickListener {
    public static final String HASBINDDEVICEID = "hasbinddeviceid";
    public static Cartoons cartoons;
    ViewPager pager;
    TextView change_num;
    RelativeLayout show_came_ry;
    EditText user_et, password_et;
    TextView show_can;
    String did;
    SharedPreferences sharedPreferences;
    public final static int REQUEST_CAMERA = 1;


    /**
     * 拍照时存储拍照结果的临时文件,test git push,ddd
     */
    private File mTmpFile;
    TestFragment mfragment1;


    @Override
    public int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        super.initView();
        setBackgroundResource(R.mipmap.boby_bg);
        sharedPreferences = getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据

        JMessageClient.registerEventReceiver(this);
        did = sharedPreferences.getString("DID", "");

        if (TextUtils.isEmpty(did)) {
            Intent intent = new Intent(this, LauchActivity.class);
            startActivity(intent);
            finish();
            return;
        }

        verifyPermissions(MainActivity.this, Manifest.permission.RECORD_AUDIO,
                new String[]{Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE}
                , 0x01, new PermissionCallBack() {

                    @Override
                    public void onGranted() {

                    }

                    @Override
                    public void onDenied() {
                    }
                });
        initUpdate();

        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        SharedPrefUtils prefUtils = Utils.getSharedPrefCommonFile();
        if (!rid.isEmpty()) {
            LogUtil.d("liaoyong:regid:" + rid);
            prefUtils.put("pushId", rid);
        } else {
            Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show();
        }
        BaseApplication.getInstance().sendReportEvent("setpushid", prefUtils.get("pushId", "").toString());

        change_num = (TextView) findViewById(R.id.change_num);
        show_came_ry = (RelativeLayout) findViewById(R.id.show_came_ry);
        user_et = (EditText) findViewById(R.id.user_et);
        password_et = (EditText) findViewById(R.id.password_et);
        show_can = (TextView) findViewById(R.id.show_can);
        change_num.setOnClickListener(this);
        show_came_ry.setOnClickListener(this);
        change_num.setOnClickListener(this);

        initViewPager();
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        //后台数据服务，不阻塞ui显示
        //注册极光im
        initChangeChat(did, "123456");
        getGuideAudio();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(mfragment1!=null) {
            mfragment1.onRefresh(true);
        }
    }

    /* 检测更新
         */
    private void initUpdate() {
        String checkUrl = String.format("%s?deviceid=13916014463&version_code=%d", Constant.VerionUrl, getAppVersion(this));
        UpdateManager.checkUpdate(this, false, true, checkUrl, new UpdateManager.CheckUpdateListener() {
            @Override
            public void onResult(final boolean result, Bundle bundle, int ext) {
            }
        });
    }

    /**
     * 获取当前应用版本code
     *
     * @return
     */
    public static int getAppVersion(Context context) {
        int versionCode = 0;
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode; //版本名
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }


    /**
     * 修改串号
     *
     * @param chuanhao
     * @param password
     */
    public void initChangeChat(String chuanhao, String password) {
        User user = new User();
        user.setMobile(chuanhao);
        user.setPassword(password);
        user.setRole(1);
        SharedPrefUtils prefUtils = Utils.getSharedPrefCommonFile();
        prefUtils.put("user", user);
        loginJG(chuanhao, password);
    }

    public void onEvent(ContactNotifyEvent event) {
        String reason = event.getReason();
        String fromUsername = event.getFromUsername();
        String appkey = event.getfromUserAppKey();

        switch (event.getType()) {
            case invite_received://收到好友邀请
                LogUtils.i("XHX", "XHX:" + fromUsername + "收到好友请求");
                ContactManager.acceptInvitation(fromUsername, null, new BasicCallback() {
                    @Override
                    public void gotResult(int responseCode, String responseMessage) {
                        if (0 == responseCode) {
                            //接收好友请求成功
                            LogUtils.i("XHX", "XHX:接收好友请求成功");
                        } else {
                            LogUtils.i("XHX", "XHX:接收好友请求失败");

                        }
                    }
                });
                break;
            case invite_accepted://对方接收了你的好友邀请
                LogUtils.i("XHX", "XHX:" + fromUsername + "对方接受了你的好友请求");
                break;
            case invite_declined://对方拒绝了你的好友邀请
                LogUtils.i("XHX", "XHX:" + fromUsername + "对方拒绝了你的好友请求");

                break;
            case contact_deleted://对方将你从好友中删除
                LogUtils.i("XHX", "XHX:" + fromUsername + "对方删除了你的好友请求");

                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        JMessageClient.unRegisterEventReceiver(this);
        super.onDestroy();
    }

    private void initViewPager() {
        mfragment1 = new TestFragment();
        Bundle data = new Bundle();
        data.putInt("currentPage", 1);
        mfragment1.setArguments(data);//通过Bundle向Activity中传递值

        ArrayList<Fragment> fragmentList = new ArrayList<Fragment>();
        fragmentList.add(mfragment1);

        String[] titles = new String[]{"故事"};
        //ViewPager的adapter
        FragmentPagerAdapter adapter = new TabPageIndicatorAdapter(getSupportFragmentManager(), fragmentList, titles);
        pager = (ViewPager) findViewById(R.id.activity_content);
        pager.setAdapter(adapter);
        pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        //实例化TabPageIndicator然后设置ViewPager与之关联
        /**自定义部分属性*/
        SlidingTabLayout tabLayout = (SlidingTabLayout) findViewById(R.id.activity_tabbar);
        tabLayout.setViewPager(pager);
    }

    public void verifyPermissions(Activity activity, String permission, String[] reqestPermissions, int requestCode, PermissionCallBack callBack) {
        int checkPermission = ActivityCompat.checkSelfPermission(activity, permission);
        if (checkPermission != 0) {
            ActivityCompat.requestPermissions(activity, reqestPermissions, requestCode);
        } else {
            callBack.onGranted();
        }
    }

    /**
     * 注册极光推送
     */
    private void bingMessage(final String userName, final String password) {
        JMessageClient.register(userName, password, new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String registerDesc) {
                if (responseCode == 0) {
                    LogUtils.i("XHX", "XHX:" + "注册成功");
                    loginJG(userName, password);
                } else {
                    LogUtils.i("XHX", "XHX:" + "注册失败");
                    Log.i("RegisterActivity", "JMessageClient.register " + ", responseCode = " + responseCode + " ; registerDesc = " + registerDesc);
                }
            }
        });
    }

    /**
     * 登录极光IM
     */
    private void loginJG(final String userName, final String password) {
        JMessageClient.login(userName, password, new BasicCallback() {
            @Override
            public void gotResult(int responseCode, String LoginDesc) {
                LogUtil.d("login sucess..");
                if (responseCode == 0) {
                    User user = new User();
                    user.setMobile(userName);
                    SharedPrefUtils prefUtils = Utils.getSharedPrefCommonFile();
                    prefUtils.put("user", user);
                    LogUtils.i("XHX", "XHX:" + "登录成功");
                } else {
                    bingMessage(userName, password);
                    LogUtils.i("XHX", "XHX:" + "IM绑定失败");
                }
            }
        });
    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.trans);
        toolbar.setTitle(getString(R.string.app_name));
        toolbar.setLeftShow(false);
        toolbar.setRightText("实时通话");
        toolbar.setRightTextColor(R.color.black);
        toolbar.setTitleColor(R.color.black);
        //toolbar.setVisibility(View.GONE);
        toolbar.setOnRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // openPhotoPicker();
//                if(mfragment1!=null) {
//                    mfragment1.onRefresh(true);
//                }
                startActivity(new Intent(MainActivity.this, VoiceCallingActivity.class));
            }
        });
        toolbar.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View view) {
                Intent intent = new Intent(MainActivity.this, LauchActivity.class);
                startActivity(intent);
                finish();
                return false;
            }
        });

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.show_story:
                pager.setCurrentItem(0);

                break;
            case R.id.show_chat:
                pager.setCurrentItem(1);
                break;
            case R.id.show_can:

                if (TextUtils.isEmpty(user_et.getText().toString()) || TextUtils.isEmpty(password_et.getText().toString())) {
                    ToastUtil.displayShortToast("用户名或密码不能为空");
                    break;
                }
                UserInfo myInfo = JMessageClient.getMyInfo();
                if (myInfo != null) {
                    JMessageClient.logout();

                }
                Utils.saveUserEntry(null);
                initChangeChat(user_et.getText().toString(), password_et.getText().toString());
                show_came_ry.setVisibility(View.GONE);
                break;
            case R.id.show_came_ry:
                show_came_ry.setVisibility(View.GONE);
                break;
            case R.id.change_num:
                show_came_ry.setVisibility(View.VISIBLE);
                break;
        }
    }

    public void openPhotoPicker(Cartoons cartoons) {
        this.cartoons = cartoons;
        LogUtils.i("XHX", "XHX返回的对象：" + cartoons.toString());

        if (Build.VERSION.SDK_INT >= 23) {
            int checkCallPhonePermission = ContextCompat.checkSelfPermission(MainActivity.this,
                    Manifest.permission.CAMERA);
            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 222);
                return;
            } else {
                openCamra();//调用具体方法
            }
        } else {
            openCamra();//调用具体方法
        }
    }

    private void openCamra() {
        try {
            Intent cameraIntent=new Intent(MainActivity.this,customCamer.class);
                startActivityForResult(cameraIntent, REQUEST_CAMERA);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            //就像onActivityResult一样这个地方就是判断你是从哪来的。
            case 222:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    openCamra();
                } else {
                    // Permission Denied
                    Toast.makeText(MainActivity.this, "很遗憾你把相机权限禁用了。请务必开启相机权限享受我们提供的服务吧。", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.i("onActivityResult", "---requestCode = " + requestCode + "---resultCode = " + resultCode);
        if (resultCode == getActivity().RESULT_OK && requestCode == REQUEST_CAMERA) {
            mTmpFile=new File(data.getStringExtra("date"));
            if (mTmpFile != null) {
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + mTmpFile.getAbsolutePath())));
                String fileUrl = mTmpFile.getAbsolutePath();
                LogUtils.i("XHX", "返回地址1：" + fileUrl);
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessageDelayed(0, 0);
                    }
                }).start();
                uploadStoryInfo(fileUrl);
            } else {
                if (cartoons != null) {
                    LogUtils.i("XHX", "XHX执行了页面跳转");
                    Intent intent = new Intent(MainActivity.this, EnglishInfoActivity.class);
                    intent.putExtra("info", cartoons);
                    startActivity(intent);
                    cartoons = null;
                }
            }
        } else if (resultCode == getActivity().RESULT_OK && requestCode == 2) {
            Uri uri = data.getData();
            if (uri == null) {
                return;
            }
            String cropImagePath = getRealFilePathFromUri(getActivity(), uri);
            LogUtils.i("XHX", "返回地址：" + cropImagePath);
        }

    }

    /*
   * 上传图片文件
   *
   * */
    public void uploadStoryInfo(String fileName) {

        NetWorkUtils.upload(MainActivity.this, Constant.UPLOAD_PATH, new File(fileName), new NetWorkUtils.IProgressListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                LogUtils.i("XHX", "ACTIVITY接受到了：" + result.toString());
                try {
                    String res = resObj.getJSONObject("response").optString("url");
                    sendToday(res);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onProgress(int index, long totalBytes, long surplusBytes, boolean done) {
                LogUtils.i("XHX", "进度：" + surplusBytes + ";总进度：" + totalBytes);
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils.i("XHX", "ACTIVITY接受到了失败：" + result.toString());
                ToastUtil.displayShortToast("上传故事失败");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessageDelayed(1, 0);
                    }
                }).start();
            }
        });

    }

    /**
     * 上传宝宝选择的数据
     * TODO 没有正式数据
     */
    protected void sendToday(String url) {
        Map<String, String> hashMap = new HashMap<>();
        // {"result":{"rc":0,"rd":"getsendtobaby ok"},"response":{"cartoons":[],"storys":[]}}
        User user = Utils.getUserEntry();
        //deviceid=HB234567&babyphotourl=http://123.jpg

        hashMap.put("deviceid", user.getMobile());
        hashMap.put("babyphotourl", url);
        LogUtils.i("XHX", "ID:" + user.getMobile() + ";babyphotourl:" + url);
        NetWorkUtils.post(MainActivity.this, "setbabyphoto", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                ToastUtil.displayShortToast("照片上传成功");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessageDelayed(1, 0);
                    }
                }).start();
                if (cartoons != null) {
                    LogUtils.i("XHX", "XHX执行了页面跳转");
                    Intent intent = new Intent(MainActivity.this, EnglishInfoActivity.class);
                    intent.putExtra("info", cartoons);
                    startActivity(intent);
                    cartoons = null;
                } else {
                    LogUtils.i("XHX", "cartoons为空");

                }
            }

            @Override
            public void onError(String result, String code, String msg) {
                LogUtils
                        .i("XHX", "XHXERROR:" + result);
                ToastUtil.displayShortToast("照片上传失败");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.sendEmptyMessageDelayed(1, 0);
                    }
                }).start();
            }
        });


    }

    /**
     * 根据Uri返回文件绝对路径
     * 兼容了file:///开头的 和 content://开头的情况
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePathFromUri(final Context context, final Uri uri) {
        if (null == uri) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if (scheme == null)
            data = uri.getPath();
        else if (ContentResolver.SCHEME_FILE.equals(scheme)) {
            data = uri.getPath();
        } else if (ContentResolver.SCHEME_CONTENT.equals(scheme)) {
            Cursor cursor = context.getContentResolver().query(uri, new String[]{MediaStore.Images.ImageColumns.DATA}, null, null, null);
            if (null != cursor) {
                if (cursor.moveToFirst()) {
                    int index = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                    if (index > -1) {
                        data = cursor.getString(index);
                    }
                }
                cursor.close();
            }
        }
        return data;
    }


    /**
     * 获取引导播放的语音信息
     * TODO 没有正式数据
     */
    protected void getGuideAudio() {
        Map<String, String> hashMap = new HashMap<>();
        User user = Utils.getUserEntry();

        hashMap.put("deviceid", user.getMobile());
        NetWorkUtils.post(MainActivity.this, "getguideaudio", hashMap, true, new NetWorkUtils.IListener() {

            @Override
            public void onSuccess(String result, JSONObject resObj) {
                try {
                    sharedPreferences.edit().putString("guidetakephotoaudio",
                            resObj.getJSONObject("response").getString("guidetakephotoaudio")).commit();
                    sharedPreferences.edit().putString("guidethanksaudio",
                            resObj.getJSONObject("response").getString("guidethanksaudio")).commit();
                    sharedPreferences.edit().putString("guideselectstory",
                            resObj.getJSONObject("response").getString("guideselectstory")).commit();
                    sharedPreferences.edit().putString(HASBINDDEVICEID,
                            resObj.getJSONObject("response").getString("bindphoneid")).commit();

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(String result, String code, String msg) {


            }
        });


    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 0:
                    showProgressDialog(MainActivity.this, "正在上传图片……");
                    break;
                case 1:
                    // 按照初始位置播放
                    dismissProgressDialog(MainActivity.this);
                    break;

            }
        }

    };
    private static CommonProgressDialog dialog;

    public static void showProgressDialog(Context mContext, final String showStr) {
        if (mContext != null) {
            if (dialog == null) {
                dialog = new CommonProgressDialog(mContext);
                dialog.setTitle(showStr);
                dialog.setCancelable(true);
                dialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface d, int keyCode, KeyEvent event) {
                        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
                            dialog.dismiss();
                            dialog = null;
                        }
                        return false;
                    }
                });
                dialog.show();
            } else {
                if (!dialog.isShowing()) {
                    dialog.show();
                }
            }
        }
    }

    public static void dismissProgressDialog(Context mContext) {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }


}